Ext.onReady(function() {
	var citys = [{'code':'1100','sfmc':'北京','Ip':'https://zjfpcyweb.bjsat.gov.cn:443','address':'https://zjfpcyweb.bjsat.gov.cn:443'},
			 {'code':'1200','sfmc':'天津','Ip':'https://fpcy.tjsat.gov.cn:443','address':'https://fpcy.tjsat.gov.cn:443'},
			 {'code':'1300','sfmc':'河北','Ip':'https://fpcy.he-n-tax.gov.cn:82','address':'https://fpcy.he-n-tax.gov.cn:82'},
			 {'code':'1400','sfmc':'山西','Ip':'https://fpcy.tax.sx.cn:443','address':'https://fpcy.tax.sx.cn:443'},
			 {'code':'1500','sfmc':'内蒙古','Ip':'https://fpcy.nm-n-tax.gov.cn:443','address':'https://fpcy.nm-n-tax.gov.cn:443'},
			 {'code':'2100','sfmc':'辽宁','Ip':'https://fpcy.tax.ln.cn:443','address':'https://fpcy.tax.ln.cn:443'},
			 {'code':'2102','sfmc':'大连','Ip':'https://fpcy.dlntax.gov.cn:443','address':'https://fpcy.dlntax.gov.cn:443'},
			 {'code':'2200','sfmc':'吉林','Ip':'https://fpcy.jl-n-tax.gov.cn:4432','address':'https://fpcy.jl-n-tax.gov.cn:4432'},
			 {'code':'2300','sfmc':'黑龙江','Ip':'https://fpcy.hl-n-tax.gov.cn:443','address':'https://fpcy.hl-n-tax.gov.cn:443'},
			 {'code':'3100','sfmc':'上海','Ip':'https://fpcyweb.tax.sh.gov.cn:1001','address':'https://fpcyweb.tax.sh.gov.cn:1001'},
			 {'code':'3200','sfmc':'江苏','Ip':'https://fpdk.jsgs.gov.cn:80','address':'https://fpdk.jsgs.gov.cn:80'},
			 {'code':'3300','sfmc':'浙江','Ip':'https://fpcyweb.zjtax.gov.cn:443','address':'https://fpcyweb.zjtax.gov.cn:443'},
			 {'code':'3302','sfmc':'宁波','Ip':'https://fpcy.nb-n-tax.gov.cn:443','address':'https://fpcy.nb-n-tax.gov.cn:443'},
			 {'code':'3400','sfmc':'安徽','Ip':'https://fpcy.ah-n-tax.gov.cn:443','address':'https://fpcy.ah-n-tax.gov.cn:443'},
			 {'code':'3500','sfmc':'福建','Ip':'https://fpcyweb.fj-n-tax.gov.cn:443','address':'https://fpcyweb.fj-n-tax.gov.cn:443'},
			 {'code':'3502','sfmc':'厦门','Ip':'https://fpcy.xm-n-tax.gov.cn','address':'https://fpcy.xm-n-tax.gov.cn'},
			 {'code':'3600','sfmc':'江西','Ip':'https://fpcy.jxgs.gov.cn:82','address':'https://fpcy.jxgs.gov.cn:82'},
			 {'code':'3700','sfmc':'山东','Ip':'https://fpcy.sd-n-tax.gov.cn:443','address':'https://fpcy.sd-n-tax.gov.cn:443'},
			 {'code':'3702','sfmc':'青岛','Ip':'https://fpcy.qd-n-tax.gov.cn:443','address':'https://fpcy.qd-n-tax.gov.cn:443'},
			 {'code':'4100','sfmc':'河南','Ip':'https://fpcy.ha-n-tax.gov.cn','address':'https://fpcy.ha-n-tax.gov.cn'},
			 {'code':'4200','sfmc':'湖北','Ip':'https://fpcy.hb-n-tax.gov.cn:443','address':'https://fpcy.hb-n-tax.gov.cn:443'},
			 {'code':'4300','sfmc':'湖南','Ip':'https://fpcy.hntax.gov.cn:8083','address':'https://fpcy.hntax.gov.cn:8083'},
			 {'code':'4400','sfmc':'广东','Ip':'https://fpcy.gd-n-tax.gov.cn:443','address':'https://fpcy.gd-n-tax.gov.cn:443'},
			 {'code':'4403','sfmc':'深圳','Ip':'https://fpcy.szgs.gov.cn:443','address':'https://fpcy.szgs.gov.cn:443'},
			 {'code':'4500','sfmc':'广西','Ip':'https://fpcy.gxgs.gov.cn:8200','address':'https://fpcy.gxgs.gov.cn:8200'},
			 {'code':'4600','sfmc':'海南','Ip':'https://fpcy.hitax.gov.cn:443','address':'https://fpcy.hitax.gov.cn:443'},
			 {'code':'5000','sfmc':'重庆','Ip':'https://fpcy.cqsw.gov.cn:80','address':'https://fpcy.cqsw.gov.cn:80'},
			 {'code':'5100','sfmc':'四川','Ip':'https://fpcy.sc-n-tax.gov.cn:443','address':'https://fpcy.sc-n-tax.gov.cn:443'},
			 {'code':'5200','sfmc':'贵州','Ip':'https://fpcy.gz-n-tax.gov.cn:80','address':'https://fpcy.gz-n-tax.gov.cn:80'},
			 {'code':'5300','sfmc':'云南','Ip':'https://fpcy.yngs.gov.cn:443','address':'https://fpcy.yngs.gov.cn:443'},
			 {'code':'5400','sfmc':'西藏','Ip':'https://fpcy.xztax.gov.cn:81','address':'https://fpcy.xztax.gov.cn:81'},
			 {'code':'6100','sfmc':'陕西','Ip':'https://fpcyweb.sn-n-tax.gov.cn:443','address':'https://fpcyweb.sn-n-tax.gov.cn:443'},
			 {'code':'6200','sfmc':'甘肃','Ip':'https://fpcy.gs-n-tax.gov.cn:443','address':'https://fpcy.gs-n-tax.gov.cn:443'},
			 {'code':'6300','sfmc':'青海','Ip':'https://fpcy.qh-n-tax.gov.cn:443','address':'https://fpcy.qh-n-tax.gov.cn:443'},
			 {'code':'6400','sfmc':'宁夏','Ip':'https://fpcy.nxgs.gov.cn:443','address':'https://fpcy.nxgs.gov.cn:443'},
			 {'code':'6500','sfmc':'新疆','Ip':'https://fpcy.xj-n-tax.gov.cn:443','address':'https://fpcy.xj-n-tax.gov.cn:443'}];
	var yzmInfo = {}, ip,mainIp = "https://inv-veri.chinatax.gov.cn/";
	var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"查询中，请稍后..."});
	var win = Ext.create('Ext.window.Window',{
		title: 'MM-好像目前只支持北京上海深圳的发票查询',
		constrain: true,
		closable: false,
		modal: false,
		items: [{
			margin: 2,
			border: false,
			xtype: 'form',
			baseCls: 'x-form',
			width: 500,
			layout: 'column',
			defaults: {
				xtype: 'textfield',
				labelAlign: 'right',
				labelWidth: 70,
				margin: 2,
				columnWidth: 1
			},
			items: [{
				xtype: 'filefield',
				fieldLabel: '发票文件',
				allowBlank: false,
				name: 'file_',
				emptyText: '选择pdf发票文件，然后点击获取信息',
				buttonText: '选择',
				columnWidth: 0.8
			},{
				xtype: 'button',
				columnWidth: 0.2,
				text: '获取信息',
				handler: function(btn){
					var form = btn.up('form');
					form.submit({
						clientValidation: true,
					    url: 'getInvoiceInfo',
					    timeout : 60000,
					    submitEmptyText : false,
					    method: 'POST',
					    waitMsg :'数据交互中...',
					    success: function(me, action) {
					    	var fpInfo = action.result;
					    	form.down('[name=fpdm]').setValue(fpInfo.fpdm);
					    	form.down('[name=fphm]').setValue(fpInfo.fphm);
					    	form.down('[name=fprq]').setValue(fpInfo.fprq);
					    	form.down('[name=fpje]').setValue(fpInfo.fpje);
					    	getyzmImg(fpInfo.fpdm);
					    },
					    failure: function(me, action) {
					    	if(action.failureType){
						        switch (action.failureType) {
						            case Ext.form.action.Action.CLIENT_INVALID:
						                Ext.Msg.alert('提示', '请选择文件');
						                break;
						            case Ext.form.action.Action.CONNECT_FAILURE:
						                Ext.Msg.alert('提示', '连接异常，请稍候重试或联系系统管理员');
						                break;
						            case Ext.form.action.Action.SERVER_INVALID:
						               Ext.Msg.alert('提示', action.result.msg);
						               break;
						            default :
						               Ext.Msg.alert('提示', action.result.msg);
						       }
					    	}
					    }
					});
				}
			},{
				fieldLabel: '发票代码',
				emptyText: '发票代码',
				name: 'fpdm'
			},{
				fieldLabel: '发票号码',
				emptyText: '请输入发票号码',
				name: 'fphm'
			},{
				fieldLabel: '发票日期',
				emptyText: '请输入发票日期，格式YYYYMMDD',
				name: 'fprq'
			},{
				fieldLabel: '发票校验码',
				emptyText: '请输入至少后6位发票校验码',
				name: 'fpje'
			},{
				columnWidth: 0.3,
				itemId: 'validCode',
				emptyText: '验证码',
				fieldLabel: '验证码'
			},{
				xtype: 'image',
				columnWidth: 0.3,
				itemId: 'image',
				height: 40
			},{
				columnWidth: 0.4,
				xtype: 'displayfield',
				itemId: 'imageText',
				height: 40,
				hideLabel: true
			}],
			buttonAlign: 'center',
			buttons: [{
				text: '识别',
				disabled: true,
				itemId: 'recognizeBtn',
				handler: function(btn){
					var form = btn.up('form');
					var fpje = form.down('[name=fpje]').getValue();
					if(fpje.length <= 6){
						Ext.Msg.alert('提示', '发票校验码至少6位');
						return;
					}
					fpje = fpje.substring(fpje.length - 6);
					var validCode = form.down('#validCode').getValue();
					if(validCode && validCode.length > 0){
						checkInvoice(form.down('[name=fpdm]').getValue(), form.down('[name=fphm]').getValue(),
							form.down('[name=fprq]').getValue(), fpje, validCode);
					}else{
						Ext.Msg.alert('提示', '请输入验证码');
					}
				}
			}]
		}]
	});
	win.show();
	var getyzmImg = function(fpdm){
		loadMask.show();
		var dqdm = null;
		if (fpdm.length == 12) {
			dqdm = fpdm.substring(1, 5);
		} else {
			dqdm = fpdm.substring(0, 4);
		}
		if (dqdm != "2102" && dqdm != "3302" && dqdm != "3502" && dqdm != "3702"
				&& dqdm != "4403") {
			dqdm = dqdm.substring(0, 2) + "00";
		}
		for (var i = 0; i < citys.length; i++) {
			if (dqdm == citys[i].code) {
				ip = citys[i].Ip + "/WebQuery";
				break;
			}
		}
		$.ajax({
			type : "post",
			url : ip + "/yzmQuery",
			data : {
				'fpdm' : fpdm,
				'r' : Math.random()
			},
			dataType : "jsonp",
			jsonp : "callback",
			success : function(jsonData) {
				loadMask.hide();
				yzmInfo = jsonData;
				var key1 = jsonData.key1;
				if (key1 == "003") {
					Ext.Msg.alert("警告", "验证码请求次数过于频繁，请1分钟后再试！");
				} else if (key1 == "005") {
					Ext.Msg.alert("警告", "非法请求!");
				} else if (key1 == "010") {
					Ext.Msg.alert("提示", "网络超时，请重试！(01)");
				} else if (key1 == "fpdmerr") {
					Ext.Msg.alert("提示", "请输入合法发票代码!");
				} else if (key1 == "024") {
					Ext.Msg.alert("警告", "24小时内验证码请求太频繁，请稍后再试！");
				} else if (key1 == "016") {
					Ext.Msg.alert("警告", "服务器接收的请求太频繁，请稍后再试！");
				} else if (key1 == "020") {
					Ext.Msg.alert("警告", "由于查验行为异常，涉嫌违规，当前无法使用查验服务！");
				} else if (key1 != "") {
					var image = win.down('#image');
					image.setSrc("data:image/png;base64," + key1);
					if(!image.clickEvent){
						image.getEl().on('click',
							function(e, t){
			    				getyzmImg(fpdm);
		    	    		}
			    	    );
					}
					image.clickEvent = true;
					var texttt;
					if (jsonData.key4 == '00') {
						texttt = "请输入验证码文字";
					} else if (jsonData.key4 == '01') {
						texttt = "请输入验证码图片中<font color=\"red\" size=\"4\"	style=\"background:#C0C0C0\">红色</font>文字";
					} else if (jsonData.key4 == '02') {
						texttt = "请输入验证码图片中<font color=\"yellow\"	size=\"4\" style=\"background:#C0C0C0\">黄色</font>文字";
					} else if (jsonData.key4 == '03') {
						texttt = "请输入验证码图片中<font color=\"blue\" size=\"4\" style=\"background:#C0C0C0\">蓝色</font>文字";
					}
					win.down('#imageText').setValue(texttt);
					win.down('#recognizeBtn').setDisabled(false);
				}
			},
			timeout : 5000,
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				loadMask.hide();
				Ext.Msg.alert("警告","错误");
			}
		});
	}
	var checkInvoice = function(fpdm, fphm, kprq, fpje, yzm){
		loadMask.show();
		var yzmSj = yzmInfo.key2;
		var swjgmc = "";
		var fplx = "10";
		$.ajax({
			type : "post",
			url : ip + "/query",
			dataType : "jsonp",
			data : {
				'fpdm': fpdm,
				'fphm': fphm,// 发票号码
				'kprq': kprq, // 开票日期
				'fpje': fpje,// 校验码
				'fplx': fplx, //fplx
				'yzm': yzm,//验证码
				'yzmSj': yzmSj,// 验证码时间
				'index': yzmInfo.key3,
				'iv': CryptoJS.lib.WordArray.random(128 / 8).toString(CryptoJS.enc.Hex),//iv
				'salt': CryptoJS.lib.WordArray.random(128 / 8).toString(CryptoJS.enc.Hex)
			},
			jsonp : "callback",
			success : function(jsonData) {
				loadMask.hide();
				var cyjgdm = jsonData.key1;
				if (cyjgdm == "1") {
					//标志为1，是试运行且代码为非北京，上海，深圳的。防范前台没卡住的情况
					Ext.Msg.alert("提示", "该省尚未开通发票查验功能！");
				} else if (cyjgdm == "001") {
					Ext.Msg.alert("验证通过", "该发票是合法的");
                    //var t = "var aa17=fpdm+\"≡\"+fphm+\"≡\"+swjgmc+\"≡\"+jsonData.key2+\"≡\"+yzmSj";
                    //这里是从后台传来的
                    eval(jsonData.key5);
                    var hwxx = jsonData.key3;
                    var jmbz = "";
                    var aesUtil = new AesUtil(128, 100);
                    if (jsonData.key4.trim() != '') {
                        jmbz = aesUtil.decrypt(jsonData.key8, jsonData.key7, jsonData.key9, jsonData.key4); //解密备注
                    }
                    var jmsort = aesUtil.decrypt(jsonData.key8, jsonData.key7, jsonData.key9, jsonData.key10); //解密排序顺序
                    //var tt = "var result={\"template\":3,\"c342\":fplx,\"d64b\":aa17,\"dbd2\":hwxx,\"jmbz\":jmbz,\"sort\":jmsort}";//这个也是后台传的
                    eval(jsonData.key6);
                    var jsname = jsonData.key11 + ".js"; //用哪个js，从后台传过来。还需要一个配置页面
                    //key7也需要获取，如果未获取到，则用上面定义的jsname，否则，使用key7代入的jsname。
                    var browser = getBrowser();
                    if (browser == "edge" || browser == "firefox") {
                        sessionStorage["jsname"] = jsname;
                        $.getScript(mainIp + "js/" + jsname,
                        function() { //加载,并执行回调函数 (回调函数是空的)
                            show_dialog(1100, 700, "cyjgedge" + fplx + ".html", result);
                        });
                    } else if (browser == "ie8") { //ie8不能通过方法参数获取到相应数据，所以特殊处理
                        sessionStorage["jsname"] = jsname;
                        sessionStorage["browser"] = "ie8";
                        var str = JSON.stringify(result);
                        sessionStorage["result"] = str;
                        $.getScript(mainIp + "js/" + jsname,
                        function() { //加载,并执行回调函数 (回调函数是空的)
                            show_dialog(1100, 700, "cyjgedge" + fplx + ".html", result);
                        });
                    } else {
                        sessionStorage["jsname"] = jsname;
                        $.getScript(mainIp + "js/" + jsname,
                        function() { //加载,并执行回调函数 
                            sessionStorage["rule"] = rule;
                            window.showModalDialog('cyjg' + fplx + '.html', result, "dialogTop:10px;dialogWidth:1100px;dialogHeight:700px;");
                        });
                    }
				} else if (cyjgdm == "002") {
					Ext.Msg.alert("提示", "超过该张发票当日查验次数(请于次日再次查验)!");
				} else if (cyjgdm == "003") {
					Ext.Msg.alert("提示", "发票查验请求太频繁，请稍后再试！");
				} else if (cyjgdm == "004") {
					Ext.Msg.alert("提示", "超过服务器最大请求数，请稍后访问!");
				} else if (cyjgdm == "005") {
					Ext.Msg.alert("提示", "请求不合法!");
				} else if (cyjgdm == "020") {
					Ext.Msg.alert("提示", "由于查验行为异常，涉嫌违规，当前无法使用查验服务！");
				} else if (cyjgdm == "006") {
					Ext.Msg.alert("提示", "不一致");
                    param = {
                        'fplx': fplx,
                        'swjg': swjgmc,
                        'fpdm': fpdm,
                        'fphm': fphm,
                        'kprq': kprq,
                        'kjje': fpje,
                        'cysj': yzmSj,
                        'setText': "不一致"
                    };
                    window.showModalDialog('jgbyz.html', param, "dialogWidth:700px;dialogHeight:400px;center:yes;scroll:no");
				} else if (cyjgdm == "007") {
					Ext.Msg.alert("提示", "验证码失效!");
				} else if (cyjgdm == "008") {
					Ext.Msg.alert("提示", "验证码错误!");
				} else if (cyjgdm == "009") {
					Ext.Msg.alert("提示", "查无此票");
				} else if (cyjgdm == "rqerr") {
					Ext.Msg.alert("提示", "当日开具发票可于次日进行查验！");
				} else if (cyjgdm == "010") {
					var etype = jsonData.key2;
					Ext.Msg.alert(etype);
					if (etype == 'inredis') {
						etype = "(02)";
					} else if (etype == 'weberr') {
						etype = "(03)";
					}
					Ext.Msg.alert("警告", "网络超时，请重试！" + etype, "系统错误");
				} else if (cyjgdm == "010_") {
					Ext.Msg.alert("警告", "网络超时，请重试！(05)", "系统错误");
				} else {
					Ext.Msg.alert("警告", "网络超时，请重试！(04)", "系统错误");
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				loadMask.hide();
				Ext.Msg.alert("警告","错误");
			}
		});
	}
});